package com.ali.ttt.webSocket.domain;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * @Author : yuxl
 * @create 2024/7/8 10:06 AM
 */
@Slf4j
@Data
public class ServerSession {

    public static final AttributeKey<ServerSession> SESSION_KEY =    AttributeKey.valueOf("SESSION_KEY");

    /**
     * 用户实现服务端会话管理的核心
     */
    //通道
    private Channel channel;

    //session唯一标示
    private final String sessionId;

    private User user;


    public ServerSession(Channel channel) {
        //完成正向绑定
        this.channel = channel;
        this.sessionId = buildNewSessionId();
    }

    public static void closeSession(ChannelHandlerContext ctx) {
    }

    public ServerSession reverseBind() {
        log.info(" ServerSession 绑定会话 " + channel.remoteAddress());
        channel.attr(ServerSession.SESSION_KEY).set(this);
        SessionMap.inst().addSession(this);
        return this;
    }


    private static String buildNewSessionId() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-", "");
    }
}
